package com.zjut.an.news.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.zjut.an.util.module.PageModule;


/**
 * A data access object (DAO) providing persistence and search support for
 * AnNews entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.zjut.an.news.dao.AnNews
 * @author MyEclipse Persistence Tools
 */

public class AnNewsDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory.getLogger(AnNewsDAO.class);
	// property constants
	public static final String NE_ID = "neId";
	public static final String TITLE = "title";
	public static final String FULLTITLE = "fulltitle";
	public static final String ABSTRACT_ = "abstract_";
	public static final String TITLEURL = "titleurl";
	public static final String REDTITLE = "redtitle";
	public static final String TAG = "tag";
	public static final String AUTHOR = "author";
	public static final String SOURCE = "source";
	public static final String CONTENT = "content";
	public static final String PICTURE = "picture";
	public static final String HIT = "hit";
	public static final String VIEWTYPE = "viewtype";
	public static final String ISCHECK = "ischeck";
	public static final String ISTOP = "istop";
	public static final String ISRECOMMEND = "isrecommend";
	public static final String ISHOT = "ishot";
	public static final String SCORE = "score";
	public static final String PLACE = "place";
	public static final String DEL = "del";
	public static final String WC_ID = "wcId";
	public static final String AD_ID = "adId";

	public void sort(Criteria criteria, String sort, String order) {
		if (sort!=null && order!=null) {
			if (order.equals("asc")) {
				criteria.addOrder(Order.asc(sort));
			} else {
				criteria.addOrder(Order.desc(sort));
			}
		} else {
			criteria.addOrder(Order.desc(NE_ID));
		}
	}
	
	protected void initDao() {
		// do nothing
	}

	public void save(AnNews transientInstance) {
		log.debug("saving AnNews instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void update(AnNews transientInstance) {
		log.debug("updating AnNews instance");
		try {
			getHibernateTemplate().update(transientInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}

	public void delete(AnNews persistentInstance) {
		log.debug("deleting AnNews instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public AnNews findById(java.lang.Integer id) {
		log.debug("getting AnNews instance with id: " + id);
		try {
			AnNews instance = (AnNews) getHibernateTemplate().get(
					"com.zjut.an.news.dao.AnNews", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(AnNews instance) {
		log.debug("finding AnNews instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding AnNews instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from AnNews as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByTitle(Object title) {
		return findByProperty(TITLE, title);
	}

	public List findByFulltitle(Object fulltitle) {
		return findByProperty(FULLTITLE, fulltitle);
	}

	public List findByAbstract_(Object abstract_) {
		return findByProperty(ABSTRACT_, abstract_);
	}

	public List findByTitleurl(Object titleurl) {
		return findByProperty(TITLEURL, titleurl);
	}

	public List findByRedtitle(Object redtitle) {
		return findByProperty(REDTITLE, redtitle);
	}

	public List findByTag(Object tag) {
		return findByProperty(TAG, tag);
	}

	public List findByAuthor(Object author) {
		return findByProperty(AUTHOR, author);
	}

	public List findBySource(Object source) {
		return findByProperty(SOURCE, source);
	}

	public List findByContent(Object content) {
		return findByProperty(CONTENT, content);
	}

	public List findByPicture(Object picture) {
		return findByProperty(PICTURE, picture);
	}

	public List findByHit(Object hit) {
		return findByProperty(HIT, hit);
	}

	public List findByViewtype(Object viewtype) {
		return findByProperty(VIEWTYPE, viewtype);
	}

	public List findByIscheck(Object ischeck) {
		return findByProperty(ISCHECK, ischeck);
	}

	public List findByIstop(Object istop) {
		return findByProperty(ISTOP, istop);
	}

	public List findByIsrecommend(Object isrecommend) {
		return findByProperty(ISRECOMMEND, isrecommend);
	}

	public List findByIshot(Object ishot) {
		return findByProperty(ISHOT, ishot);
	}

	public List findByScore(Object score) {
		return findByProperty(SCORE, score);
	}

	public List findByPlace(Object place) {
		return findByProperty(PLACE, place);
	}

	public List findByDel(Object del) {
		return findByProperty(DEL, del);
	}

	public List findByWcId(Object wcId) {
		return findByProperty(WC_ID, wcId);
	}

	public List findByAdId(Object adId) {
		return findByProperty(AD_ID, adId);
	}

	public List findAll() {
		log.debug("finding all AnNews instances");
		try {
			String queryString = "from AnNews";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public List findByHql(final int pageNumber ,final int pageSize, final String hql, final Object[] values){
		log.debug("finding AnNews instance by hql");
	    return (List<AnNews>) super.getHibernateTemplate().execute(new HibernateCallback(){
	        public Object doInHibernate(Session session) throws HibernateException, SQLException {
	            Query query=session.createQuery(hql);
	            if (values != null) {// 为hql语句传入参数
					for (int i = 0; i < values.length; i++) {
						query.setParameter(i, values[i]);
					}
				}
	            return query.setFirstResult((pageNumber-1)*pageSize).setMaxResults(pageSize).list();
	        }
	    });
	}

	@SuppressWarnings("unchecked")
	public int findCountByHql(final String hql, final Object[] values) {
		log.debug("finding the number of AnNews instance");
		try {
			return (Integer) super.getHibernateTemplate().execute(new HibernateCallback(){
		        public Object doInHibernate(Session session) throws HibernateException, SQLException {
		            Query query=session.createQuery(hql);
		            if (values != null) {// 为hql语句传入参数
						for (int i = 0; i < values.length; i++) {
							query.setParameter(i, values[i]);
						}
					}
					return ((Long)query.uniqueResult()).intValue();
		        }
		    });
		} catch (RuntimeException re) {
			log.error("find the number of AnNews instance failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public PageModule findByInstance(final int pageNumber ,final int pageSize, String sort, String order, final AnNews obj){
		try {
			int startIndex = (pageNumber - 1) * pageSize;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			List list;
			Criteria criteria = session.createCriteria(AnNews.class);
			
			if (!isEmpty(obj.getTitle())) {
				criteria.add(Restrictions.like(TITLE, obj.getTitle(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getAuthor())) {
				criteria.add(Restrictions.like(AUTHOR, obj.getAuthor(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getIscheck())) {
				criteria.add(Restrictions.like(ISCHECK, obj.getIscheck(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getIshot())) {
				criteria.add(Restrictions.like(ISHOT, obj.getIshot(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getIsrecommend())) {
				criteria.add(Restrictions.like(ISRECOMMEND, obj.getIsrecommend(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getIstop())) {
				criteria.add(Restrictions.like(ISTOP, obj.getIstop(),MatchMode.ANYWHERE));
			}
			if (null != obj.getAdId()) {
				criteria.add(Restrictions.eq(AD_ID, obj.getAdId()));
			}
			if (null != obj.getAnWebclass()) {
				criteria.add(Restrictions.eq("anWebclass", obj.getAnWebclass()));
			}			
			if (!isEmpty(obj.getViewtype())) {
				criteria.add(Restrictions.like(VIEWTYPE, obj.getViewtype(),MatchMode.ANYWHERE));
			}
			
			this.sort(criteria, sort, order);
			
			criteria.setFirstResult(startIndex);
			criteria.setMaxResults(pageSize);
			list = criteria.list();
			session.close();
			return new PageModule(pageNumber, pageSize, countByInstance(obj), list);
		} catch (RuntimeException re) {
			log.error("findByInstance failed", re);
			throw re;
		}
	}
	
	public int countByInstance(final AnNews obj) {
		log.debug("finding the number of AnNews instance");
		try {
			int count = 0;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Criteria criteria = session.createCriteria(AnNews.class);

			if (!isEmpty(obj.getTitle())) {
				criteria.add(Restrictions.like(TITLE, obj.getTitle(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getAuthor())) {
				criteria.add(Restrictions.like(AUTHOR, obj.getAuthor(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getIscheck())) {
				criteria.add(Restrictions.like(ISCHECK, obj.getIscheck(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getIshot())) {
				criteria.add(Restrictions.like(ISHOT, obj.getIshot(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getIsrecommend())) {
				criteria.add(Restrictions.like(ISRECOMMEND, obj.getIsrecommend(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getIstop())) {
				criteria.add(Restrictions.like(ISTOP, obj.getIstop(),MatchMode.ANYWHERE));
			}
			if (null != obj.getAdId()) {
				criteria.add(Restrictions.eq(AD_ID, obj.getAdId()));
			}
			if (null != obj.getAnWebclass()) {
				criteria.add(Restrictions.eq("anWebclass", obj.getAnWebclass()));
			}	
			if (!isEmpty(obj.getViewtype())) {
				criteria.add(Restrictions.like(VIEWTYPE, obj.getViewtype(),MatchMode.ANYWHERE));
			}
			
			count = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
			session.close();
			return count;
		} catch (RuntimeException re) {
			log.error("find the number of AnNews instance failed", re);
			throw re;
		}
	}
	
	public void excuteHql(String hql) throws Exception {
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		try {
			Query query = session.createQuery(hql);
			query.executeUpdate();
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		} finally {
			session.close();
		}
	}
	
	private boolean isEmpty(String value) {
		if (value==null || value.trim().length()==0) {
			return true;
		}
		return false;
	}

	public AnNews merge(AnNews detachedInstance) {
		log.debug("merging AnNews instance");
		try {
			AnNews result = (AnNews) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(AnNews instance) {
		log.debug("attaching dirty AnNews instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(AnNews instance) {
		log.debug("attaching clean AnNews instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static AnNewsDAO getFromApplicationContext(ApplicationContext ctx) {
		return (AnNewsDAO) ctx.getBean("AnNewsDAO");
	}
}